/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: QuoteApi.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.quote;

import android.text.TextUtils;

import java.util.List;

import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.network.BParamsBuilder;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.params.GetParams;
import io.bhex.baselib.network.params.IParams;
import io.bhex.sdk.Urls;
import io.bhex.sdk.data_manager.NetWorkApiManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.otc.bean.OrderCreateResponse;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.DealPriceSocketRequest;
import io.bhex.sdk.quote.bean.DealPriceSocketResponse;
import io.bhex.sdk.quote.bean.DepthSocketRequest;
import io.bhex.sdk.quote.bean.DepthSocketResponse;
import io.bhex.sdk.quote.bean.KLineSocketRequst;
import io.bhex.sdk.quote.bean.KLineSocketResponse;
import io.bhex.sdk.quote.bean.RealTimeSocketRequest;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.quote.bean.TopNSocketRequest;
import io.bhex.sdk.socket.NetWorkObserver;

public class QuoteApi  {

    /**
     * GetKline get kLine Data
     * @param klineType
     * @param exchangeId
     * @param symbol
     * @param limit
     */
    public static void SubKline(String klineType, String exchangeId, String symbol, String limit, NetWorkObserver<KLineSocketResponse> observer) {
        KLineSocketRequst socketBaseBean = new KLineSocketRequst();
        socketBaseBean.topic = "kline_" + klineType;
        socketBaseBean.event = "sub";
        socketBaseBean.symbol = exchangeId + "." + symbol;
        socketBaseBean.limit = limit;
        KLineSocketRequst.Params klineParams = new KLineSocketRequst.Params();
        klineParams.limit = limit;
        klineParams.binary = true;
        socketBaseBean.setParams(klineParams);

        GetParams params = BParamsBuilder.get()
                .url(Urls.API_KLINE_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId + "." + symbol)
                .addParam(Fields.FIELD_INTERVAL, klineType)
                //.addParam(Fields.FIELD_FROM, fromTime)
                //.addParam(Fields.FIELD_TO, toTime)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, KLineSocketResponse.class, observer);
    }

    /**
     * UnSubKline
     * @param klineType
     */
    public static void UnSubKline(String klineType){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("kline_" + klineType);
    }

    /**
     * GetKlineHistory
     * @param klineType
     * @param exchangeId
     * @param symbol
     * @param toTime
     * @param limit
     * @param observer
     */
    public static void GetKlineHistory(String klineType, String exchangeId, String symbol, Long toTime,String limit, NetWorkObserver<KLineSocketResponse> observer) {

            GetParams params = BParamsBuilder.get()
                    .url(Urls.API_KLINE_URL)
                    .addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                    .addParam(Fields.FIELD_SYMBOL, exchangeId + "." + symbol)
                    .addParam(Fields.FIELD_INTERVAL, klineType)
                    //.addParam(Fields.FIELD_FROM, fromTime)
                    .addParam(Fields.FIELD_TO, toTime)
                    .build();
            KLineSocketRequst socketBaseBean = new KLineSocketRequst();
            socketBaseBean.topic = "kline_" + klineType;
            socketBaseBean.event = "req";
            socketBaseBean.symbol = exchangeId + "." + symbol;
            socketBaseBean.limit = limit;
            //socketBaseBean.from = String.valueOf(fromTime);
            socketBaseBean.to = String.valueOf(toTime);
            socketBaseBean.key = socketBaseBean.topic + socketBaseBean.event;

            NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, KLineSocketResponse.class, observer);

    }


    public static void GetKlineHistoryExt(String klineType, String exchangeId, String symbol, Long toTime,String limit, SimpleResponseListener<KLineSocketResponse> listener) {

        GetParams params = BParamsBuilder.get()
                .url(Urls.API_KLINE_URL)
                .addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId + "." + symbol)
                .addParam(Fields.FIELD_INTERVAL, klineType)
                .addParam(Fields.FIELD_LIMIT, limit)
                //.addParam(Fields.FIELD_FROM, fromTime)
                .addParam(Fields.FIELD_TO, toTime)
                .build();


        HttpUtils.getInstance().request(params, KLineSocketResponse.class,listener);


    }

    /**
     *
     * @param exchangeId
     * @param symbol
     * @param observer
     */
    public static void SubDepthData(String exchangeId,  String symbol, NetWorkObserver<DepthSocketResponse> observer){
        QuoteApi.UnSubDepthData();
        DepthSocketRequest socketBaseBean = new DepthSocketRequest();
        socketBaseBean.topic = "diffDepth";
        socketBaseBean.event = "sub";
        socketBaseBean.symbol = exchangeId + "." + symbol;
        socketBaseBean.limit = 100;
        DepthSocketRequest.Params depthParams = new DepthSocketRequest.Params();
        depthParams.binary = true;
        socketBaseBean.params = depthParams;

        IParams params = BParamsBuilder.get()
                .url(Urls.API_DEPTHVIEW_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId+ "." + symbol)
                .addParam(Fields.FIELD_LIMIT, 40)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, DepthSocketResponse.class, observer);
    }

    /**
     * UnSubDepthData
     */
    public static void UnSubDepthData(){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("diffDepth");
    }

    /**
     * SubTicker
     * @param exchangeId
     * @param symbol
     * @param observer
     * @return
     */
    public static void SubTicker(String exchangeId,  String symbol, NetWorkObserver<TickerListBean> observer){
        if(TextUtils.isEmpty(symbol))
            return;
        QuoteApi.UnSubTickers();
        RealTimeSocketRequest socketBaseBean = new RealTimeSocketRequest();
        socketBaseBean.topic = "realtimes";
        socketBaseBean.event = "sub";
        socketBaseBean.symbol = exchangeId + "." + symbol;
        RealTimeSocketRequest.Params paramsBean = new RealTimeSocketRequest.Params();
        paramsBean.binary = true;
        socketBaseBean.params = paramsBean;

        IParams params = BParamsBuilder.get()
                .url(Urls.API_TICKER_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId+ "." + symbol)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, TickerListBean.class, observer);
    }

    public static void RequestTicker(String exchangeId,  String symbol, SimpleResponseListener<TickerListBean> observer){

        IParams params = BParamsBuilder.get()
                .url(Urls.API_TICKER_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId+ "." + symbol)
                .build();

        HttpUtils.getInstance().request(params,TickerListBean.class, observer);

    }

    /**
     * 请求 tickers
     * @param list
     * @param observer
     */
    public static void RequestTickers(List<CoinPairBean> list, SimpleResponseListener<TickerListBean> observer){
        String symbolsListStr = getSymbolsListStr(list);

        IParams params = BParamsBuilder.get()
                .url(Urls.API_TICKER_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, symbolsListStr)
                .build();

        HttpUtils.getInstance().request(params,TickerListBean.class, observer);

    }

    /**
     * 拼接行情参数
     *
     * @return
     */
    private static String getSymbolsListStr(List<CoinPairBean> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
//            symbolMap.clear();
            for (CoinPairBean coinPairBean : list) {
                if (coinPairBean != null) {
//                symbolMap.put(coinPairBean.getSymbolId(),coinPairBean);
                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                    if (stringBuffer.toString().length() > 0) {
                        stringBuffer.append("," + symbol);
                    } else {
                        stringBuffer.append(symbol);
                    }
                }
            }

        }
        return stringBuffer.toString();
    }


    /**
     * UnSubTopN
     * @param subKey
     */
    public static void UnSubTopN(String subKey){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork(subKey);
    }

    /**
     * 请求/订阅行情排序的前N个行情
     * @param marketType
     * @param observer
     * @return
     */
    public static void SubTopN(int marketType, NetWorkObserver<TickerListBean> observer){

        String key = "topN"+marketType;

        QuoteApi.UnSubTopN(key);

        String orgId = SymbolDataManager.GetInstance().getOrgId();

        TopNSocketRequest socketBaseBean = new TopNSocketRequest();
        socketBaseBean.topic = "topN";
        socketBaseBean.event = "sub";
        socketBaseBean.key = key;
        TopNSocketRequest.ParamsBean paramsBean = new TopNSocketRequest.ParamsBean();
        paramsBean.limit = AppData.TICKER.TOPN_LIMIT;
        paramsBean.type = marketType;
        paramsBean.binary = true;
        paramsBean.org = orgId;
        socketBaseBean.params = paramsBean;

        IParams params = BParamsBuilder.get()
                .url(Urls.API_QUOTE_V1_BROKER_TOP_N_URL)
                .addParam(Fields.FIELD_LIMIT, AppData.TICKER.TOPN_LIMIT)
                .addParam(Fields.FIELD_TYPE, marketType)
                .addParam(Fields.FIELD_ORG, orgId)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, TickerListBean.class, observer);
    }

    /**
     * SubTickers
     * @param symbols
     * @param observer
     * @return
     */
    public static void SubTickers(String symbols, NetWorkObserver<TickerListBean> observer){

        if(TextUtils.isEmpty(symbols))
            return;
        QuoteApi.UnSubTickers();
        RealTimeSocketRequest socketBaseBean = new RealTimeSocketRequest();
        socketBaseBean.topic = "realtimes";
        socketBaseBean.event = "sub";
        socketBaseBean.symbol = symbols;
        RealTimeSocketRequest.Params paramsBean = new RealTimeSocketRequest.Params();
        paramsBean.binary = true;
        socketBaseBean.params = paramsBean;

        IParams params = BParamsBuilder.get()
                .url(Urls.API_TICKER_URL)
                .addParam(Fields.FIELD_SYMBOL, symbols)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, TickerListBean.class, observer);
    }

    /**
     * UnSubTicker
     */
/*    public static void UnSubTicker(){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("realtimes");
    }*/

    /**
     * UnSubTickers
     */
    public static void UnSubTickers(){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("realtimes");
    }

    /**
     * SubTradeData
     * @param exchangeId
     * @param symbol
     * @param observer
     */
    public static void SubTradeData(String exchangeId,  String symbol, NetWorkObserver<DealPriceSocketResponse> observer){
        DealPriceSocketRequest socketBaseBean = new DealPriceSocketRequest();
        socketBaseBean.topic = "trade";
        socketBaseBean.event = "sub";
        socketBaseBean.symbol = exchangeId+ "." + symbol;
        //socketBaseBean.limit = DATE_MAX_SIZE;
        DealPriceSocketRequest.Params paramsBean = new DealPriceSocketRequest.Params();
        paramsBean.binary = true;
        socketBaseBean.params = paramsBean;

        GetParams params = BParamsBuilder.get()
                .url(Urls.API_LATEST_TRADE_URL)
                //.addParam(Fields.FIELD_EXCHANGE_ID, exchangeId)
                .addParam(Fields.FIELD_SYMBOL, exchangeId+ "." + symbol)
                .build();

        NetWorkApiManager.getQuoteInstance().SubRequestNetwork(socketBaseBean, params, DealPriceSocketResponse.class, observer);
    }

    /**
     * UnSubTradeData
     */
    public static void UnSubTradeData(){
        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("trade");
    }
}
